﻿//------------------------------------------------------------------------------
// Written for CP2011 Project @ JCU, 2011
// By Drewan O'Brien
//
// Listens for TCP socket connections form any IP address on port 9000
//------------------------------------------------------------------------------

using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace BluSteamServer.Model
{
    public class ServerListener 
    {
        #region Fields

        private TcpListener _listener;
        private const int DEFAULT_PORT = 9000;

        #endregion

        #region Constructors

        public ServerListener()
        {
            _listening = false;
        }

        #endregion

        #region Properties

        public bool IsListening
        {
            get { return _listening; }
        }
        private bool _listening;

        public IMessageHandler MessageHandler
        {
            get { return _messageHandler; }
        }
        private IMessageHandler _messageHandler;

        #endregion

        #region Methods

        public void Start()
        {
            if (IsListening) return;

            // create thread to listen for connections
            Thread listenerThread = new Thread(new ThreadStart(Listen));
            listenerThread.IsBackground = true;
            listenerThread.Start();

            _listening = true;
        }

        public void Listen()
        {
            _listener = new TcpListener(IPAddress.Any, DEFAULT_PORT);

            // continue listening for connections while server is running
            while (IsListening)
            {
                _listener.Start();
                Socket socket = _listener.AcceptSocket();
                Debug.WriteLine("connected");

                if (socket != null)
                    DispatchClient(socket);
            }
        }

        /// <summary>
        /// Dispatch each connected client socket to be handled on its own thread.
        /// </summary>
        public void DispatchClient(Socket socket)
        {
            _messageHandler = new MessageHandler(socket);
        }

        public void Stop()
        {
            if (!IsListening) return;

            _listener.Stop();
            _listening = false;
        }
        
        // make a list if the message handlers if the server is stopped iterate the list and stop each messageListen

        #endregion
    }
}
